package com.mdx.controller;

import com.github.pagehelper.PageInfo;
import com.mdx.entity.EbookCategory;
import com.mdx.entity.EbookEntry;
import com.mdx.mapper.CategoryMapper;
import com.mdx.service.CategoryService;
import com.mdx.service.EntryService;
import com.mdx.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/entry")
@Slf4j
public class EntryController {

    @Autowired
    private EntryService entryService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/list")
    public String list(Model model,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "5") Integer size,
                       Integer categoryid){
        PageInfo<EbookEntry> pageInfo = entryService.getByCategoryId(page, size, categoryid);
        model.addAttribute("pageInfo",pageInfo);
        List<EbookCategory> categoryList = categoryService.getAll();
        model.addAttribute("categoryList",categoryList);
        model.addAttribute("categoryid",categoryid);
        return "/entry_list";
    }

    @RequestMapping("/add-ui")
    public String addUI(Model model){
        List<EbookCategory> categoryList = categoryService.getAll();
        model.addAttribute("categoryList",categoryList);
        return "/entry_add";
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public ResultVo delete(@PathVariable Integer id){
        entryService.delete(id);
        return new ResultVo(0,"",null);
    }

    @RequestMapping("/update-ui")
    public String updateUI(Integer id,Model model){
        EbookEntry entry = entryService.getById(id);
        model.addAttribute("entry",entry);
        List<EbookCategory> categoryList = categoryService.getAll();
        model.addAttribute("categoryList",categoryList);
        return "/entry_update";
    }

    @RequestMapping("/add")
    @ResponseBody
    public ResultVo add(EbookEntry ebookEntry){
        entryService.add(ebookEntry);
        return new ResultVo(0,"",null);
    }

    @RequestMapping("/update")
    @ResponseBody
    public ResultVo update(EbookEntry ebookEntry){
        entryService.update(ebookEntry);
        return new ResultVo(0,"",null);
    }
}
